import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.utils import formataddr


def send_email(report_file):
    # 邮件发送者和接收者信息
    sender = '1718932352@qq.com'
    receiver = '1718932352@qq.com'
    sender_name = 'Test Automation'
    subject = '自动化测试报告'

    # QQ邮箱 SMTP 服务器的配置
    smtp_server = 'smtp.qq.com'
    smtp_port = 465
    smtp_user = sender
    smtp_password = 'wczkqdoigfdyeigj'  # 使用QQ邮箱生成的授权码

    # 创建一个邮件对象
    msg = MIMEMultipart()
    msg['From'] = formataddr((sender_name, sender))
    msg['To'] = receiver
    msg['Subject'] = subject

    # 邮件正文
    body = "您好，\n\n附件为自动化测试的测试报告，请查收。\n\nBest regards,\n测试小赛"
    msg.attach(MIMEText(body, 'plain', 'utf-8'))

    # 添加测试报告文件作为附件
    with open(report_file, 'rb') as file:
        # report = MIMEApplication(file.read())
        report = MIMEText(file.read(), 'html', 'utf-8')
        report.add_header('Content-Disposition', 'attachment', filename=report_file)
        msg.attach(report)

    # 使用 SMTP 发送邮件
    try:
        with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
            server.login(smtp_user, smtp_password)
            server.sendmail(sender, receiver, msg.as_string())
        print('邮件发送成功')
    except Exception as e:
        print(f"邮件发送失败: {e}")


# 调用函数发送邮件，指定要发送的测试报告文件
send_email('report2024-10-13-15-13-42.html')
